import { ElMessage } from 'element-plus'
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { start, close } from '@/utils/nprogress'

declare module 'vue-router'{
  interface _RouteRecordBase {
    hidden?: boolean | string | number,
  }
}
const Login = () =>
  import('@/views/Login/index.vue')
const Layout = () =>
  import('@/Layout/index.vue')
const Home = () =>
  import('@/views/Home/index.vue')
const User1 = () =>
  import('@/views/User/Test1.vue')
const User2 = () =>
  import('@/views/User/Test2.vue')
const Page404 = () =>
  import('@/views/404/index.vue')
const PiniaDemo = () =>
  import('@/views/PiniaDemo/index.vue')

const routes:Array<RouteRecordRaw> = [{
  path: '/login',
  name: 'login',
  component: Login,
  hidden: true,
},
{
  path: '/:cathchAll(.*)',
  name: '404',
  component: Page404,
  hidden: true,
},
{
  path: '/',
  redirect: '/home/index',
  component: Layout,
  children: [
    {
      path: '/home/index',
      component: Home,
      name: 'Home',
      meta: {
        title: '首页',
        icon: 'iconfont icon-shouye',
      },
    },
    {
      path: '/pinia',
      component: PiniaDemo,
      name: 'PiniaDemo',
      meta: {
        title: 'Pinia_Demo',
        icon: 'iconfont icon-boluo',
      },
    },
    {
      path: '/user',
      redirect: '/user/test1',
      meta: { title: '用户管理', icon: 'iconfont icon-yonghuguanli' },
      children: [
        {
          path: '/user/test1',
          component: User1,
          name: 'User1',
          meta: { title: '测试1' },
        },
        {
          path: '/user/test2',
          component: User2,
          name: 'User2',
          meta: { title: '测试2' },
        },
      ],
    },
  ],
},
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})
router.beforeEach((to, from, next) => {
  start()
  if (to.path === '/login' && sessionStorage.getItem('token') === null) {
    ElMessage.error('请先登录')
    next('/login')
    close()
  } else next()
})

router.afterEach(() => {
  close()
})
export default router
